import tkinter as tk
import random
import time

class Minesweeper:
    def __init__(self, master, rows=10, cols=10, mines=10):
        self.master = master
        self.master.title("扫雷")
        self.master.resizable(False, False)
        
        # 游戏设置
        self.rows = rows
        self.cols = cols
        self.mines = mines
        self.cell_size = 30
        self.game_over = False
        self.first_click = True
        self.start_time = 0
        self.flags = 0
        
        # 创建UI
        self.create_ui()
        
        # 初始化游戏
        self.reset_game()
    
    def create_ui(self):
        # 创建顶部控制区域
        control_frame = tk.Frame(self.master)
        control_frame.pack(fill=tk.X)
        
        # 计时器
        self.timer_var = tk.StringVar(value="000")
        timer_label = tk.Label(control_frame, textvariable=self.timer_var, font=("Digital-7", 24), bg="black", fg="red", width=5)
        timer_label.pack(side=tk.LEFT, padx=10, pady=10)
        
        # 剩余地雷数
        self.mines_var = tk.StringVar(value=str(self.mines))
        mines_label = tk.Label(control_frame, textvariable=self.mines_var, font=("Digital-7", 24), bg="black", fg="red", width=5)
        mines_label.pack(side=tk.RIGHT, padx=10, pady=10)
        
        # 重置按钮
        self.reset_button = tk.Button(control_frame, text="😊", font=("Arial", 16), command=self.reset_game)
        self.reset_button.pack(side=tk.TOP, pady=10)
        
        # 创建游戏网格
        self.grid_frame = tk.Frame(self.master)
        self.grid_frame.pack()
        
        # 创建单元格按钮
        self.buttons = []
        self.cells = []
        
        for i in range(self.rows):
            row_buttons = []
            row_cells = []
            for j in range(self.cols):
                # 创建按钮
                button = tk.Button(self.grid_frame, width=2, height=1, font=("Arial", 12), 
                                  relief=tk.RAISED, bg="#C0C0C0")
                button.grid(row=i, column=j, padx=1, pady=1)
                
                # 绑定鼠标事件
                button.bind("<Button-1>", lambda event, x=i, y=j: self.left_click(x, y))
                button.bind("<Button-3>", lambda event, x=i, y=j: self.right_click(x, y))
                
                row_buttons.append(button)
                row_cells.append({"mine": False, "revealed": False, "flagged": False, "number": 0})
            
            self.buttons.append(row_buttons)
            self.cells.append(row_cells)
    
    def reset_game(self):
        # 重置游戏状态
        self.game_over = False
        self.first_click = True
        self.start_time = 0
        self.flags = 0
        self.mines_var.set(str(self.mines))
        self.timer_var.set("000")
        self.reset_button.config(text="😊")
        
        # 重置单元格状态
        for i in range(self.rows):
            for j in range(self.cols):
                self.cells[i][j] = {"mine": False, "revealed": False, "flagged": False, "number": 0}
                self.buttons[i][j].config(text="", bg="#C0C0C0", relief=tk.RAISED, state=tk.NORMAL)
        
        # 设置计时器更新
        self.update_timer()
    
    def update_timer(self):
        if not self.game_over and not self.first_click:
            elapsed_time = int(time.time() - self.start_time)
            self.timer_var.set(f"{elapsed_time:03d}")
            self.master.after(1000, self.update_timer)
    
    def setup_mines(self, first_i, first_j):
        # 随机放置地雷，避开第一次点击的位置
        mine_positions = []
        
        while len(mine_positions) < self.mines:
            i = random.randint(0, self.rows - 1)
            j = random.randint(0, self.cols - 1)
            
            # 确保不在第一次点击的位置及其周围，并且不重复
            if (abs(i - first_i) <= 1 and abs(j - first_j) <= 1) or (i, j) in mine_positions:
                continue
            
            mine_positions.append((i, j))
        
        # 放置地雷
        for i, j in mine_positions:
            self.cells[i][j]["mine"] = True
        
        # 计算每个单元格周围的地雷数
        for i in range(self.rows):
            for j in range(self.cols):
                if not self.cells[i][j]["mine"]:
                    count = 0
                    for dx in [-1, 0, 1]:
                        for dy in [-1, 0, 1]:
                            if 0 <= i + dx < self.rows and 0 <= j + dy < self.cols:
                                if self.cells[i + dx][j + dy]["mine"]:
                                    count += 1
                    self.cells[i][j]["number"] = count
    
    def left_click(self, i, j):
        # 处理左键点击
        if self.game_over or self.cells[i][j]["revealed"] or self.cells[i][j]["flagged"]:
            return
        
        # 第一次点击时设置地雷
        if self.first_click:
            self.first_click = False
            self.start_time = time.time()
            self.setup_mines(i, j)
            self.update_timer()
        
        # 检查是否点击到地雷
        if self.cells[i][j]["mine"]:
            self.game_over = True
            self.reset_button.config(text="😵")
            self.reveal_all_mines()
            return
        
        # 显示当前单元格
        self.reveal_cell(i, j)
        
        # 检查是否获胜
        if self.check_win():
            self.game_over = True
            self.reset_button.config(text="😎")
            self.flag_all_mines()
    
    def right_click(self, i, j):
        # 处理右键点击(标记地雷)
        if self.game_over or self.cells[i][j]["revealed"]:
            return
        
        if not self.cells[i][j]["flagged"]:
            # 标记地雷
            if self.flags < self.mines:
                self.cells[i][j]["flagged"] = True
                self.buttons[i][j].config(text="🚩", bg="#C0C0C0")
                self.flags += 1
        else:
            # 取消标记
            self.cells[i][j]["flagged"] = False
            self.buttons[i][j].config(text="", bg="#C0C0C0")
            self.flags -= 1
        
        # 更新剩余地雷数显示
        self.mines_var.set(str(self.mines - self.flags))
    
    def reveal_cell(self, i, j):
        # 显示单元格内容
        if self.cells[i][j]["revealed"] or self.cells[i][j]["flagged"]:
            return
        
        self.cells[i][j]["revealed"] = True
        number = self.cells[i][j]["number"]
        
        # 设置按钮样式
        self.buttons[i][j].config(relief=tk.SUNKEN, bg="#E0E0E0")
        
        # 显示数字或空白
        if number > 0:
            colors = ["", "blue", "green", "red", "purple", "maroon", "cyan", "black", "gray"]
            self.buttons[i][j].config(text=str(number), fg=colors[number])
        elif number == 0:
            # 空白单元格，自动展开周围的单元格
            for dx in [-1, 0, 1]:
                for dy in [-1, 0, 1]:
                    if 0 <= i + dx < self.rows and 0 <= j + dy < self.cols:
                        self.reveal_cell(i + dx, j + dy)
    
    def reveal_all_mines(self):
        # 显示所有地雷
        for i in range(self.rows):
            for j in range(self.cols):
                if self.cells[i][j]["mine"]:
                    self.buttons[i][j].config(text="💣", bg="#FF0000", relief=tk.SUNKEN)
                elif self.cells[i][j]["flagged"]:
                    self.buttons[i][j].config(text="❌", bg="#FF0000", relief=tk.SUNKEN)
    
    def flag_all_mines(self):
        # 标记所有地雷(获胜时)
        for i in range(self.rows):
            for j in range(self.cols):
                if self.cells[i][j]["mine"]:
                    self.buttons[i][j].config(text="🚩", bg="#00FF00", relief=tk.SUNKEN)
    
    def check_win(self):
        # 检查是否获胜
        for i in range(self.rows):
            for j in range(self.cols):
                if not self.cells[i][j]["mine"] and not self.cells[i][j]["revealed"]:
                    return False
        return True

if __name__ == "__main__":
    root = tk.Tk()
    game = Minesweeper(root)
    root.mainloop()